package com.zw.workflowllm.controller;

import com.zw.workflowllm.dto.HolidayDTO;
import com.zw.workflowllm.mapstruct.TaskVOMapper;
import com.zw.workflowllm.service.HolidayWorkflowService;
import com.zw.workflowllm.vo.TaskVO;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/holidays")
@RequiredArgsConstructor
public class HolidayController {

    private final HolidayWorkflowService holidayWorkflowService;
    private final TaskVOMapper taskVOMapper;

    /**
     * 启动请假流程
     *
     * @param dto
     * @return
     */
    @PostMapping("/start")
    public ResponseEntity<String> startHolidayProcess(@RequestBody HolidayDTO dto) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("startDate", dto.getStartDate());
        variables.put("endDate", dto.getEndDate());
        variables.put("reason", dto.getReason());
        ProcessInstance holidayProcess = holidayWorkflowService.startHolidayProcess(dto.getEmployeeId(), variables);
        return ResponseEntity.ok(holidayProcess.getId() + "-" + holidayProcess.getName() + "-" + holidayProcess.getActivityId());
    }

    /**
     * 获取当前用户待处理的任务
     *
     * @param assigneeId 待办人ID
     * @return
     */
    @GetMapping("/tasks/{assigneeId}")
    public ResponseEntity<List<TaskVO>> getTasks(@PathVariable(name = "assigneeId") String assigneeId) {
        List<Task> tasks = holidayWorkflowService.getTasks(assigneeId);
        List<TaskVO> taskVOList = taskVOMapper.toTaskVO(tasks);
        return ResponseEntity.ok(taskVOList);
    }

    /**
     * 根据任务ID获取任务详情
     *
     * @param taskId 任务ID
     * @return
     */
    @GetMapping("/getTaskById/{taskId}")
    public ResponseEntity<TaskVO> getTaskById(@PathVariable(name = "taskId") String taskId) {
        Task taskById = holidayWorkflowService.getTaskById(taskId);
        TaskVO taskVO = taskVOMapper.toTaskVO(taskById);
        return ResponseEntity.ok(taskVO);
    }

    @PostMapping("/complete")
    public ResponseEntity<String> completeTask(@RequestParam(value = "taskId") String taskId,
                                               @RequestParam(value = "approved", required = false) Boolean approved,
                                               @RequestParam(value = "comments", required = false) String comments) {
        Map<String, Object> variables = new HashMap<>();
        if (approved != null) {
            variables.put("approved", approved);
        }
        if (comments != null && !comments.isEmpty()) {
            variables.put("comments", comments);
        }
        holidayWorkflowService.completeTask(taskId, variables);

        return ResponseEntity.ok(taskId);
    }
}
